<?php

namespace app\api\controller\lottery;

use app\admin\model\LotteryAcc;
use app\api\controller\Base;

/**
 * 抽奖小程序用户相关接口
 */
class Lotteryaccs extends Base
{

    // 登录接口
    public function login()
    {
        $gh_id = $this->request->post('gh_id');
        $code = $this->request->post('code');

        $openid = $this->get_openid($gh_id, $code);
        $acc = LotteryAcc::get(['openid' => $openid]);

        if (!$acc) {
            $acc = new LotteryAcc;
            $acc->openid = $openid;
            $acc->all_lottery = '[]';
            $acc->lucky = 0;
            $acc->is_owner = 1;
            $acc->save();
        }

        $this->result('login', $acc);
    }

    // 更新用户头像昵称信息
    public function updateAccInfo()
    {
        $openid = $this->request->post('openid');
        $nick_name = $this->request->post('nick_name');
        $avatar_url = $this->request->post('avatar_url');

        $acc = LotteryAcc::get(['openid' => $openid]);
        if ($nick_name) {
            $acc->nick_name = $nick_name;
        }
        if ($avatar_url) {
            $acc->avatar_url = $avatar_url;
        }
        if ($acc->save() !== false) {
            $this->success(1);
        } else {
            $this->error(0);
        }
    }

    // 获取当前用户所有抽奖情况
    public function get_acc_lottery_info()
    {
        $uid = $this->request->post('uid');
        $acc = LotteryAcc::get($uid);
        $data['all'] = count(json_decode($acc->all_lottery));
        $data['lucky'] = $acc->lucky;
        $this->result('login', $data);
    }
}
